package com.hmall.item.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("list")
    public PageDTO list(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {
        Page<Item> ipage = new Page<>(page, size);
        IPage<Item> pageResult = itemService.page(ipage);
        long total = pageResult.getTotal();
        List<Item> records = pageResult.getRecords();
        return new PageDTO<>(total, records);
    }

    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item findById(@PathVariable("id") Long id) {
        Item item = itemService.getById(id);
        return item;
    }

    /**
     * 新增商品
     *
     * @param item
     */
    @PostMapping
    public void save(@RequestBody Item item) {
        itemService.save(item);
    }

    /**
     * 商品上架、下架
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void status(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        Item item = itemService.getById(id);
        if (item != null) {
            item.setStatus(status);
            itemService.updateById(item);
        }
    }

    /**
     * 修改商品
     * @param itemDto
     */
    @PutMapping
    public void update(@RequestBody Item itemDto) {
        Item item = itemService.getById(itemDto.getId());
        if (item!=null&&item.getStatus()!=1){
            itemService.updateById(item);
        }
    }

    /**
     * 根据id删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id){
        Item item = itemService.getById(id);
        if (item!=null&&item.getStatus()!=1){
            itemService.removeById(id);
        }
    }


}
